from rest_framework import serializers
from user.models import SysUser
from .models import Meeting, MeetingTranscript, MeetingSummary
import random
import string
from datetime import datetime, timedelta


class MeetingSerializer(serializers.ModelSerializer):
    host_name = serializers.CharField(source='host.username', read_only=True)
    
    class Meta:
        model = Meeting
        fields = [
            'id', 'title', 'description', 'host', 'host_name', 'meeting_id', 
            'password', 'scheduled_time', 'duration', 'scheduled_end_time',
            'actual_start_time', 'actual_end_time', 'status',
            'enable_recording', 'enable_transcription',
            'enable_ai_summary', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'meeting_id', 'created_at', 'updated_at']
    
    def create(self, validated_data):
        # 生成会议ID
        validated_data['meeting_id'] = self.generate_meeting_id()
        
        # 计算结束时间
        if 'scheduled_time' in validated_data and 'duration' in validated_data:
            validated_data['scheduled_end_time'] = validated_data['scheduled_time'] + timedelta(
                minutes=validated_data['duration']
            )
        
        return super().create(validated_data)
    
    def generate_meeting_id(self):
        """生成唯一的会议ID"""
        while True:
            meeting_id = ''.join(random.choices(string.digits, k=9))
            if not Meeting.objects.filter(meeting_id=meeting_id).exists():
                return meeting_id


class MeetingTranscriptSerializer(serializers.ModelSerializer):
    class Meta:
        model = MeetingTranscript
        fields = [
            'id', 'meeting', 'speaker_name', 'text', 'confidence',
            'start_time', 'end_time', 'duration', 'audio_file', 'audio_format',
            'created_at'
        ]


class MeetingSummarySerializer(serializers.ModelSerializer):
    meeting_title = serializers.CharField(source='meeting.title', read_only=True)
    
    class Meta:
        model = MeetingSummary
        fields = [
            'id', 'meeting', 'meeting_title', 'summary_text', 'key_points',
            'action_items', 'total_words', 'total_duration',
            'generated_by', 'generated_at'
        ]


class CreateMeetingSerializer(serializers.Serializer):
    """创建会议的专用序列化器"""
    title = serializers.CharField(max_length=200)
    description = serializers.CharField(required=False, allow_blank=True)
    scheduled_time = serializers.DateTimeField()
    duration = serializers.IntegerField(min_value=15, max_value=480)
    enable_recording = serializers.BooleanField(default=True)
    enable_transcription = serializers.BooleanField(default=True)
    enable_ai_summary = serializers.BooleanField(default=True)
    
    def validate(self, attrs):
        """验证会议时间是否与现有会议冲突"""
        scheduled_time = attrs.get('scheduled_time')
        duration = attrs.get('duration')
        
        if scheduled_time and duration:
            # 计算会议结束时间
            scheduled_end_time = scheduled_time + timedelta(minutes=duration)
            
            # 查找时间冲突的会议
            # 修改逻辑：排除已取消的会议，以及已结束的会议（包括状态为scheduled/active但实际已结束的会议）
            conflicting_meetings = Meeting.objects.filter(
                scheduled_time__lt=scheduled_end_time,
                scheduled_end_time__gt=scheduled_time
            ).exclude(
                status='cancelled'  # 排除已取消的会议
            ).exclude(
                status='ended'      # 排除已结束的会议
            ).exclude(
                status__in=['scheduled', 'active'],
                actual_end_time__isnull=False  # 排除状态为scheduled/active但实际已结束的会议
            )
            
            if conflicting_meetings.exists():
                conflict_meeting = conflicting_meetings.first()
                conflict_start = conflict_meeting.scheduled_time.strftime("%Y-%m-%d %H:%M")
                conflict_end = conflict_meeting.scheduled_end_time.strftime("%H:%M")
                
                raise serializers.ValidationError({
                    'scheduled_time': f'当前时间段会议室已有预定。\n冲突会议："{conflict_meeting.title}"\n预定时间：{conflict_start} - {conflict_end}\n请选择其他时间段。'
                })
        
        return attrs
    
    def create(self, validated_data):
        # 生成会议ID
        validated_data['meeting_id'] = self.generate_meeting_id()
        
        # 计算结束时间
        validated_data['scheduled_end_time'] = validated_data['scheduled_time'] + timedelta(
            minutes=validated_data['duration']
        )
        
        return Meeting.objects.create(**validated_data)
    
    def generate_meeting_id(self):
        """生成唯一的会议ID"""
        while True:
            meeting_id = ''.join(random.choices(string.digits, k=9))
            if not Meeting.objects.filter(meeting_id=meeting_id).exists():
                return meeting_id
